<?php
namespace app\beautiful\controller\miniapp\staff\appointment;
use app\BaseController;
use app\beautiful\model\appointment\AppointmentModel;
use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\appointment\TechnicianProjectModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\SmsLogic;

class TechnicianAppointment extends BaseController{
    protected $technician;

    protected function initialize()
    {
        if(null ===$technician= TechnicianModel::where([
                ['shop_id','=',$this->request->shopId],
                ['mobile','=',$this->request->staff->mobile],
                ['status','=',1],
                ['is_delete','=',0],
            ])->find()){
            $this->error('您不是技师')->send();
            die();
        }
        $this->technician=$technician;
    
        if (!in_array(12, $this->request->staff->add_value_jurisdiction)) {
            $this->error('您没有我的预约的权限')->send();
            die();
        }
    }

    public function getTechnicianAppointmentList()
    {
        $type = $this->request->param('type/d');
        $day=$this->request->param('day');
        $return = [];
        $where = [
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$this->technician->technician_id],
            ['day','=',$day]
        ];
        switch ($type){ //查询订单的状态
            case 0: // 待确认
                $where[] = ['status','=',1];
                break;
            case 1://待到店
                $where[] = ['status','=',4];
                break;
            case 2://已完成  取消的订单也在已完成里面
                $where[] = ['status','=',8];
                break;
            case 3:
                $where[] = ['status','=',-1];
                break;
        }
        $appointment_model = new AppointmentModel();
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['appointment_time_format','cancel_time_small_format'];

        $datas=$appointment_model=$appointment_model->with(['technician'=>function($query){
            $query->field('technician_id,face,name,mobile');
        }])->where($where)->order($order)
            ->field($field)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select()
            ->append($append)
            ->toArray();


        $return['datas']=$datas;
        $return['total']=count($datas);
        return $this->success($return);
    }


    public function technicianCancelAppointment()
    {
        $appointment_id=$this->request->param('appointment_id/d',0);
        $reason=$this->request->param('reason');

        if($appointment_id==0) return $this->error('预约不存在');
        if(null == $appointment = AppointmentModel::find($appointment_id)) return $this->error('预约不存在');
        if($appointment->shop_id != $this->request->shopId) return $this->error('预约不存在');
        if($appointment->technician_id=$this->technician->technician_id) return $this->error('预约不存在');
        if(!in_array($appointment->status,[1,4])) return $this->error('预约不在状态');

        $appointment->status=-1;
        $appointment->reason=$reason;
        $appointment->cancel_time=$this->request->time();
        $appointment->operate_type=1;
        $appointment->operate_id=$this->request->staffId;
        $appointment->operate_name=$this->request->staff->name;
        $appointment->operate_mobile=$this->request->staff->mobile;
        $appointment->save();

        //发送短信给用户
        try{
            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
            if(null !== $sms_setting){
                if($sms_setting->cancel_appointment==1){
                    $sms_logic= new SmsLogic();
                    $params=[
                        'xm'=>$appointment->project_name,
                    ];
                    $sms_logic->send($this->request->shopId,[$appointment->member_mobile],$params,'cancelAppointment');
                }
            }
        }catch (\Exception $e){

        }
        return $this->success('取消预约成功');
    }

    public function technicianSureAppointment()
    {
        $appointment_id=$this->request->param('appointment_id/d',0);
        if($appointment_id==0) return $this->error('预约不存在');
        if(null == $appointment = AppointmentModel::find($appointment_id)) return $this->error('预约不存在');
        if($appointment->shop_id != $this->request->shopId) return $this->error('预约不存在');
        if($appointment->technician_id=$this->technician->technician_id) return $this->error('预约不存在');
        if($appointment->status !=1) return $this->error('预约不存在');
//        $appoint_time=strtotime($appointment->day.' '.$appointment->end_time.':00');
//        if($appoint_time<$this->request->time()) return $this->error('预约时间已过');

        $appointment->status=4;
        $appointment->save();

        //发送短信给用户
        try{
            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
            if(null !== $sms_setting){
                if($sms_setting->sure_appointment==1){
                    $sms_logic= new SmsLogic();
                    $params=[
                        'xm'=>$appointment->project_name,
                        't'=>$appointment->start_time.'-'.$appointment->end_time
                    ];
                    $sms_logic->send($this->request->shopId,[$appointment->member_mobile],$params,'sureAppointment');
                }
            }
        }catch (\Exception $e){

        }
        return $this->success('确认预约成功');
    }

    public function technicianArrivalAppointment()
    {
        $appointment_id=$this->request->param('appointment_id/d',0);
        if($appointment_id==0) return $this->error('预约不存在');
        if(null == $appointment = AppointmentModel::find($appointment_id)) return $this->error('预约不存在');
        if($appointment->shop_id != $this->request->shopId) return $this->error('预约不存在');
        if($appointment->technician_id=$this->technician->technician_id) return $this->error('预约不存在');
        if($appointment->status !=4) return $this->error('预约不在状态');

        $appointment->status=8;
        $appointment->arrival_time=$this->request->time();
        $appointment->operate_type=1;
        $appointment->operate_id=$this->request->staffId;
        $appointment->operate_name=$this->request->staff->name;
        $appointment->operate_mobile=$this->request->staff->mobile;
        $appointment->save();

        if(null !== $technician_project = TechnicianProjectModel::where([
                ['shop_id','=',$this->request->shopId],
                ['technician_id','=',$appointment->technician_id],
                ['project_id','=',$appointment->project_id],
                ['is_delete','=',0]
            ])->find()){
            $technician_project->engaged_num=$technician_project->engaged_num + 1;
            $technician_project->save();
        }
        return $this->success('操作成功');
    }

    public function getApplyAppointmentData()
    {
        $project=$this->chooseProject();

        $return = [
            'project'=>$project,
        ];

        return $this->success($return);
    }

    public function addAppointment()
    {
        $today=date("Y-m-d",$this->request->time());
        $member_id=$this->request->param('member_id/d',0);
        $project_id=$this->request->param('project_id/d',0);
        $day=$this->request->param('day');
        $start_time=$this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        if($member_id==0) return $this->error('请选择用户');
        if($project_id==0) return $this->error('请选择服务项目');
        if(empty($day)) return $this->error('请选择预约日期');
        if(false === strtotime($day.' 00.00.00')) return $this->error('请选择预约日期');
        if($day<$today) return $this->error('预约日期不能低于今天');
        if(empty($start_time) || empty($end_time)) return $this->error('请选择预约时间');
        if(false === $start_time_unix=strtotime($day.' '.$start_time.':00')) return $this->error('请选择预约开始时间');
        if($start_time_unix<=$this->request->time()) return $this->error('预约开始时间低于当前时间');
        if(false === $end_time_unix=strtotime($day.' '.$end_time.':00')) return $this->error('请选择预约结束时间');
        $interval=$end_time_unix-$start_time_unix;
        if($interval<=0) return $this->error('预约开始时间不能大于结束时间');
        if($interval%1800!=0)return $this->error('预约时间间隔必须是30分钟的整倍');

        if(null === $member = MemberModel::find($member_id)) return $this->error('用户不存在，请重新选择');
        if($member->shop_id != $this->request->shopId) return $this->error('用户不存在，请重新选择');
        if($member->is_delete != 0) return $this->error('用户不存在，请重新选择');

        if(null === $project = ProjectModel::find($project_id)) return $this->error('项目不存在，请重新选择');
        if($project->shop_id != $this->request->shopId) return $this->error('项目不存在，请重新选择');
        if($project->is_delete != 0) return $this->error('项目不存在，请重新选择');
       
        if(null === TechnicianProjectModel::where([
                ['shop_id','=',$this->request->shopId],
                ['technician_id','=',$this->technician->technician_id],
                ['project_id','=',$project_id],
                ['is_delete','=',0]
            ])->find()){
            return $this->error('您还未绑定这个项目呢');
        }

        $appointment_model=new AppointmentModel();
        $appointment_model->shop_id=$this->request->shopId;
        $appointment_model->member_id=$member_id;
        $appointment_model->member_name=$member->nick_name;
        $appointment_model->member_mobile=$member->mobile;
        $appointment_model->project_id=$project_id;
        $appointment_model->project_name=$project->abbreviation;
        $appointment_model->project_cover_img=$project->cover_img;
        $appointment_model->technician_id=$this->technician->technician_id;
        $appointment_model->technician_name=$this->technician->name;
        $appointment_model->technician_mobile=$this->technician->mobile;
        $appointment_model->day=$day;
        $appointment_model->start_time=$start_time;
        $appointment_model->end_time=$end_time;
        $appointment_model->store_id=$this->technician->store;
        $appointment_model->save();

        try{
            //发送短信给用户
            $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
            if(null !== $sms_setting){
                if($sms_setting->appointment_notice_member==1){
                    $sms_logic= new SmsLogic();
                    $params=[
                        'xm'=>$project->abbreviation,
                        't'=>$start_time.'-'.$end_time
                    ];
                    $sms_logic->send($this->request->shopId,[$member->mobile],$params,'appointmentNoticeMember');
                }
            }
        }catch (\Exception $e){

        }
        return $this->success('操作成功');
    }

    protected function chooseProject()
    {
        $project_ids=TechnicianProjectModel::where([
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$this->technician->technician_id],
            ['is_delete','=',0]
        ])->column('project_id') ?? [];

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['project_id','in',$project_ids]
        ];

        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field='project_id,abbreviation,market_price,cover_img';
        $datas=$project_model->where($where)->order($order)
            ->field($field)
            ->select()
            ->toArray();
        return $datas;
    }


}
